/**
 * 
 */
package com.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class FileHelper {
	
	public static enum CHARSET
	{
		UTF8,
		ISO88591,
		GBK,
		GB2312
	};
	
	public static enum LINE_DELIMITER
	{
		UNIX,
		DOS
	};

	static public void mkdir(String path)
	{
		int n = path.indexOf("/", 1);
		while (n != -1)
		{
			java.io.File f1 = new java.io.File(path.substring(0, n + 1));
			if (!f1.exists())
			{
				f1.mkdir();
			}
			n = path.indexOf("/", n + 1);
		}
	}
	
	static public boolean writeFile(String file, String content)
	{
		try
		{
			mkdir(file);
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(content.getBytes());
			fos.close();					
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			return false;
		}
		return true;
	}

	static public boolean writeFile(String file, String content, String charset)
	{
		try
		{
			mkdir(file);
			FileOutputStream fos = new FileOutputStream(file);
			OutputStreamWriter osw = new OutputStreamWriter(fos, charset);
//			System.out.println(osw.getEncoding());
			BufferedWriter out = new BufferedWriter(osw);
			out.write(content);
			out.close();
			osw.close();
			fos.close();					
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			return false;
		}
		return true;
	}
	
	/**
	 * 
	 * @param file
	 * @param charset : only UTF-8 GBK GB2312 and ISO-8859-1 supported, default UTF-8.
	 * @param line_delimiter : only UNIX and DOS support, defautl UNIX.
	 * @return
	 */
	static public String readFile(String file, String charset, LINE_DELIMITER delimiter)	
	{
		if (charset == null || charset.length() == 0 
				|| (!charset.equalsIgnoreCase("GBK") 
						&& !charset.equalsIgnoreCase("GB2312")
						&& !charset.equalsIgnoreCase("ISO-8859-1")
						&& !charset.equalsIgnoreCase("UTF-8")))
			charset = "UTF-8";
		
		StringBuffer sb = new StringBuffer();
		try
		{
			BufferedReader br = 
				new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
	        String line= "";
	        while((line = br.readLine()) != null)
	        {
	            sb.append(line);
	            if (delimiter != null)
	            sb.append(((delimiter == LINE_DELIMITER.DOS) ? "\r\n" : "\n"));
	        }
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
		return sb.toString();
	}
	
}
